Page({
  data: {
    selectedImagePaths: [],
    selectedImage1: '', // 当前选中的衣服图片路径
    selectedImage: '', // 当前选中的图片路径
    imageUrl:'',//生成的图片路径
    // images: ['image/1.jpg', 'image/2.jpg', 'image/3.jpg'],
    // indicatorDots: true,
    // autoplay: true,
    vertical: false,
    // interval: 2000,
    // circular: true,

    clothUrl: '',    // 保存第一个请求的返回值中的cloth
    clothId: '',
    halflenUrl: '',  // 保存第二个请求的返回值中的halflen
    halflenId: '',

    top: 0,
    hot: [
      { name: '关键词1', url: '/page/API/alert/alert' },
      { name: '关键词2', url: '/page/API/alert/alert' },
      { name: '关键词3', url: '/page/API/alert/alert' },
      { name: '关键词4', url: '/page/API/alert/alert' },
      { name: '关键词5', url: '/page/API/alert/alert' },
      { name: '关键词6', url: '/page/API/alert/alert' },
      { name: '关键词7', url: '/page/API/alert/alert' },
      { name: '关键词8', url: '/page/API/alert/alert' },
      { name: '关键词9', url: '/page/API/alert/alert' },
    ],
    tabs: ['基础组件', '扩展组件'],
    activeTab: 0, 
    titleOpacity: 1,
    shadow: false,
  },

  handleImageTap(e) {
    // 获取被点击的图片的 src
    const src = e.currentTarget.dataset.src;
    console.log('点击的图片:', src);
    this.setData({
      selectedImagePaths: [src],
      selectedImage1: src, // 更新当前选中的图片路径
    });
  },

  


  onPageScroll(e) {
    const { scrollTop } = e;
    let titleOpacity = 1 - scrollTop * 0.02;
    let shadow = false;

    if (titleOpacity < 0) {
      titleOpacity = 0;
    }

    if (titleOpacity > 1) {
      titleOpacity = 1;
    }

    if (scrollTop > 80) {
      my.setNavigationBar({
        title: '云衣科技',
      });
    } else {
      my.setNavigationBar({
        title: ' ',
      });
    }

    if (scrollTop > 320) {
      shadow = true;
    } else {
      shadow = false;
    }

    this.setData({
      shadow,
      titleOpacity,
    });
  },
  onSearchBarTap() {
    my.navigateTo({
      url: '/page/common/search/search',
    });
  },
  onTabBarTap(e) {
    const { index } = e.target.dataset
    this.setData({
      activeTab: index,
    });
  },
  onLoad() {
    my.getSystemInfo({
      success: (res) => {
        if (res.statusBarHeight && res.titleBarHeight) {
          this.setData({
            top: res.statusBarHeight + res.titleBarHeight,
          });
        }
      },
    });
  },
  goDevCenter() {
    my.navigateToMiniProgram({
      appId: '2018082061148052',
      path: 'pages/discover/discover',
      extraData: {
        "from": "miniDemo"
      }
    });
  },
  openPage(e) {
    my.navigateTo({
      url: e.target.dataset.url,
    })
  },

  // 点击图片预览
  previewImage() {
    my.previewImage({
      current: this.data.selectedImage,
      urls: [this.data.selectedImage],
    });
  },

  // 长按保存图片
  saveImage() {
    my.confirm({
      title: '保存图片',
      content: '确定保存图片到本地吗？',
      success: (res) => {
        if (res.confirm) {
          this.getPhotoFromBackend();
        }
      },
    });
  },



  onSubmit1() {
    my.chooseImage({
      sourceType: ['camera','album'],
      count: 1,
      success: (res) => {
        const path = res.apFilePaths[0];
        this.setData({
          selectedImagePaths: [path],
          selectedImage1: path, // 更新当前选中的图片路径
        });
        my.alert({
          content: '选择图片成功',
        });
      },
      fail:()=>{
        my.showToast({
          content: '取消选择', // 文字内容
        });
      }
    })

  },
  onReset1() {
    this.setData({
      selectedImagePaths:[],
      selectedImage:null,
      selectedImage1:null,
    });
  },


  onSubmit() {
    my.chooseImage({
      sourceType: ['camera','album'],
      count: 1,
      success: (res) => {
        const path = res.apFilePaths[0];
        this.setData({
          selectedImagePaths: [path],
          selectedImage: path, // 更新当前选中的图片路径
        });
        my.alert({
          content: '选择图片成功',
        });
      },
      fail:()=>{
        my.showToast({
          content: '取消选择', // 文字内容
        });
      }
    })

  },
  onReset() {
    my.alert({ title: 'You click reset' });
  },



  // 手动触发提交的按钮点击事件
  manualSubmit() {

    const filePath1 = this.data.selectedImage1;
    const filePath = this.data.selectedImage;
    let successfulUploads = 0; // 记录成功上传的计数器

    // 调用上传函数，将文件上传至后端
    // 此处是上传衣服的
    //由于文件只能一张张上传，我们选择两个上传按钮
    my.uploadFile({
      url: 'http://192.168.12.179:8080/generate/receive', // 替换为你的后端接口地址
      filePath: filePath1,
      name: 'clothPhoto',
      success: (res) => {
        // 上传成功，可以处理后端返回的数据
        console.log('衣服返回值', res.data);
        const responseData = JSON.parse(res.data);
        const clothValue = responseData.data.cloth;
        const clothId=responseData.data.clothId;
        this.setData({
          clothUrl: clothValue,
          clothId: clothId,
        });
        successfulUploads++;
        // 检查是否两个上传都成功
        if (successfulUploads === 2) {
          this.sendDataToBackend();
          successfulUploads--;
          successfulUploads--;
        }
      },
      fail: error => {
        // 上传失败，可以处理错误信息
        // console.error('上传失败', res.data);
        my.showToast({
          content: '上传失败',
          type: 'fail',
          duration: 2000,
        });
      },
    });


    // 调用上传函数，将文件上传至后端
    // 此处是上传半身照
    my.uploadFile({
      url: 'http://192.168.12.179:8080/generate/receive', // 替换为你的后端接口地址
      filePath: filePath,
      name: 'halflenPhoto',
      success: (res) => {
        // 上传成功，可以处理后端返回的数据
        console.log('半身照返回值', res);
        const responseData = JSON.parse(res.data);
        const halflenValue = responseData.data.halflen;
        const halflenId=responseData.data.halflenId;
        this.setData({
          halflenUrl: halflenValue,
          halflenId: halflenId,
        });
        successfulUploads++;
        // 检查是否两个上传都成功
        if (successfulUploads === 2) {
          this.sendDataToBackend();
          successfulUploads--;
          successfulUploads--;
        }
      },
      fail: error => {
        // 上传失败，可以处理错误信息
        // console.error('上传失败', res);
        my.showToast({
          content: '上传失败',
          type: 'fail',
          duration: 2000,
        });
      },
    });
  },

   // 向后端发起请求，传递 data 中的值
   sendDataToBackend() {
    const { clothUrl, clothId, halflenUrl, halflenId } = this.data;
    // Log the request data before sending
    console.log('Request Data:', {
    clothUrl: clothUrl,
    clothId: clothId,
    halflenUrl: halflenUrl,
    halflenId: halflenId
    });
    my.showLoading({
      content: '生成中...',  // 加载动画的提示文字
    });
    my.request({
      url: 'http://192.168.12.179:8080/generate/solve', // 替换为你的后端接口地址
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      dataType: 'json',
      timeout: 120000, // 设置超时时间为两分钟
      data: {
        clothUrl: clothUrl,
        clothId: clothId,
        halflenUrl: halflenUrl,
        halflenId: halflenId,
      },
      success: (res) => {
        // 隐藏加载动画
        my.hideLoading();
        // 后端返回成功的处理逻辑
        var imageUrl = res.data.data.generated;
        console.log(imageUrl);
        var prefix = 'http://192.168.12.179:8080/Users/1/GeneratedPhoto/';
        // 将前缀和 imageUrl 拼接起来
        var fullUrl = prefix + imageUrl;
        console.log(fullUrl);
        this.setData({
          imageUrl:fullUrl,
          selectedImage: fullUrl,
        });
        // this.getPhotoFromBackend();
        console.log('后端返回:', res);
      },
      fail: (error) => {
        // 后端请求失败，可以处理失败的情况
        console.error('请求失败:', error);
      },
    });
  },

  getPhotoFromBackend(){
    my.downloadFile({
      url: this.data.selectedImage,
      success: (res) =>{
        // 隐藏加载动画
        my.hideLoading();
        //将生成的图片显示在页面上
        this.setData({
          selectedImage: this.url,
        });
        console.log('downloadFile success：',res.apFilePath,res.tempFilePath); // apFilePath 与 tempFilePath 等价

        let tempFilePath = res.tempFilePath;
        my.saveImage({
          url: tempFilePath, // 需要保存的图片链接，此处为临时路径
          success: () => {
            my.alert({
              title: '保存成功',
              content: '图片已保存到相册'
            });
          },
          fail: () => {
            my.alert({
              title: '保存失败',
              content: '请检查权限设置'
            });
          }
        });
      },
      fail(res) {
        console.log('downloadFile fail：',res);
      },
    });
  },

  imageError(e) {
    console.log('image 发生 error 事件，携带值为', e.detail.errMsg);
  },
  onTap(e) {
    console.log('image 发生 tap 事件', e);
  },
  imageLoad(e) {
    console.log('image 加载成功', e);
  },

  handleTap: function (e) {
    my.alert({
        title: '点击按钮',
    });
},
});